import { getDictOptionsByCode } from '@/support/common';
import {
  MinusCircleOutlined,
  PlusCircleOutlined,
  PlusOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import {
  Button,
  Col,
  Dropdown,
  Form,
  Input,
  InputNumber,
  Menu,
  MenuProps,
  Radio,
  Row,
  Select,
  Space,
  Tooltip,
  Upload,
} from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle } from 'react';

interface IProps {
  isEdit: boolean;
  dicData: any[];
  dirTemplateList: any[];
  setDirTempList: (dirTempList: any[]) => void;
}

enum DirecotryEnum {
  Label = '1',
  Image = '3',
}

const directoryFieldsMap = new Map([
  [
    '1',
    {
      type: '1', // 文本
      labelName: '文本标签',
      isMutilate: 0, // 是否多行
      isRequire: 1, // 是否必选
      maxLength: undefined,
      key: undefined,
      level: undefined,
      lastOne: false,
      content: undefined,
    },
  ],
  [
    '3',
    {
      type: '3', // 图片
      labelName: '上传图片标签',
      isRequire: 1,
      format: '', // 图片格式限制
      length: undefined,
      width: undefined,
      graphics: undefined, // 图片数量限制
      size: undefined, // 图片大小限制，单位MB
      key: undefined,
      level: undefined,
      lastOne: true,
      content: [],
    },
  ],
]);

const DirTemplate = (props: IProps, ref: any) => {
  const { isEdit, dirTemplateList, setDirTempList, dicData = [] } = props;
  const [form] = Form.useForm();
  const dirKeyOptions = getDictOptionsByCode(dicData, 'dirKeyOptions');
  const dirLevel = getDictOptionsByCode(dicData, 'dirLevel');
  useImperativeHandle(ref, () => {
    return {
      form,
    };
  });

  useEffect(() => {
    // 转换type, level为字符串
    let newDirTemplateList = dirTemplateList.map(item => {
      return {
        ...item,
        type: item.type?.toString(),
        level: item.level?.toString()
      }
    })
    form.setFieldsValue({
      dirConfig: newDirTemplateList,
    });
  }, [dirTemplateList]);
  const addDirTemp = (tempKey, add) => {
    // 之前的字段列表数据
    let fieldsList = form.getFieldValue('dirConfig');
    add();
    setDirTempList([...fieldsList, directoryFieldsMap.get(tempKey)]);
  };
  const removeDirTemp = (tempKey, remove) => {
    remove(tempKey);
    let fieldsList = form.getFieldValue('dirConfig');
    setDirTempList([...fieldsList]);
  };

  // 共同表单字段字段
  const commonFormItems = name => {
    return (
      <>
        {/* 默认字段 */}
        <Col span={0}>
          <Form.Item name={[name, 'type']} key="type" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item name={[name, 'lastOne']} key="lastOne" hidden={true}>
            <Input />
          </Form.Item>
        </Col>
        <Col span={5}>
          <Space align="baseline">
            <Form.Item
              name={[name, 'level']}
              key="key"
              rules={[
                {
                  required: true,
                  message: '请选择目录层级',
                },
              ]}
            >
              <Select
                showSearch={false}
                options={dirLevel}
                allowClear
                placeholder="请选择目录层级"
                disabled={!isEdit}
                style={{ width: '110px' }}
              />
            </Form.Item>
            <Tooltip title="请选择目录层级,这是必填项！">
              <QuestionCircleOutlined />
            </Tooltip>
          </Space>
        </Col>
        <Col span={5}>
          <Space align="baseline">
            <Form.Item
              name={[name, 'key']}
              key="key"
              rules={[
                {
                  required: true,
                  message: '请选择目录关键字',
                },
              ]}
            >
              <Select
                showSearch={false}
                allowClear
                placeholder="请选择目录关键字"
                options={dirKeyOptions}
                disabled={!isEdit}
                style={{ width: '110px' }}
              />
            </Form.Item>
            <Tooltip title="请选择目录关键字,这是必填项！">
              <QuestionCircleOutlined />
            </Tooltip>
          </Space>
        </Col>
      </>
    );
  };

  const renderDirTemp = (name, fieldsValues) => {
    if (!fieldsValues) return;
    const { type, isMutilate } = fieldsValues;
    if (type.toString() === DirecotryEnum.Label) {
      return (
        <>
          <Col span={3}>
            <Form.Item
              name={[name, 'labelName']}
              key="labelName"
              initialValue={'文本标签'}
              rules={[
                {
                  validator: async (_, names): Promise<any> => {
                    if (!names) {
                      return Promise.reject(new Error('请填写文本标签'));
                    }
                  },
                },
              ]}
            >
              <Input readOnly placeholder="文本标签" bordered={false} disabled={!isEdit} />
            </Form.Item>
          </Col>
          <Col span={5}>
            <Form.Item name={[name, 'content']} key="content">
              {isMutilate === 0 ? (
                <Input placeholder="输入内容" readOnly />
              ) : (
                <Input.TextArea placeholder="输入内容" readOnly />
              )}
            </Form.Item>
          </Col>
          <Col span={5}>
            <Form.Item name={[name, 'isMutilate']} key="isMutilate">
              <Radio.Group  disabled={!isEdit}>
                <Radio value={0}>单行</Radio>
                <Radio value={1}>多行</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
          <Col span={10}>
            <Space align="baseline">
              <span>限定条件1：</span>
              <Form.Item
                name={[name, 'isRequire']}
                key="isRequire"
                label="是否必填"
                style={{ width: '254px' }}
              >
                <Radio.Group disabled={!isEdit}>
                  <Radio value={1}>必填项</Radio>
                  <Radio value={0}>非必填项</Radio>
                </Radio.Group>
              </Form.Item>
            </Space>
          </Col>
          <Col span={10}>
            <Space align="baseline">
              <span>限定条件2：</span>
              <Form.Item
                name={[name, 'maxLength']}
                key="maxLength"
                label="最长不超过"
                colon={false}
              >
                <InputNumber min={0} style={{ width: '100px' }} disabled={!isEdit} />
              </Form.Item>
              <div style={{ width: '100px' }}>个字符</div>
            </Space>
          </Col>
        </>
      );
    } else if (type.toString() === DirecotryEnum.Image) {
      return (
        <Row gutter={12}>
          <Col span={3}>
            <Form.Item
              name={[name, 'labelName']}
              key="labelName"
              rules={[
                {
                  validator: async (_, names): Promise<any> => {
                    if (!names) {
                      return Promise.reject(new Error('请填写上传图片标签'));
                    }
                  },
                },
              ]}
            >
              <Input placeholder="上传图片标签" bordered={false} disabled={!isEdit} />
            </Form.Item>
          </Col>
          <Col span={3}>
            <Form.Item>
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                disabled
              >
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传图片</div>
                </div>
              </Upload>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Row gutter={12} wrap={false}>
              <Col flex="120px">
                <Form.Item>限定条件1：</Form.Item>
              </Col>
              <Col flex="auto">
                <Form.Item name={[name, 'isRequire']} key="isRequire" label="是否必填">
                  <Radio.Group disabled={!isEdit}>
                    <Radio value={1}>必填项</Radio>
                    <Radio value={0}>非必填项</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={12} wrap={false}>
              <Col flex="0 0 120px">
                <Form.Item>限定条件2：</Form.Item>
              </Col>
              <Col flex="1 1 auto">
                <Form.Item
                  name={[name, 'format']}
                  key="format"
                  label="图片格式"
                  rules={[
                    {
                      validator: async (_, value): Promise<any> => {
                        const reg = /\.(png|jpg|gif|jpeg|webp)$/;
                        if (value) {
                          const regex = new RegExp(reg);
                          value.split(';').forEach(val => {
                            if (!regex.test(val)) {
                              return Promise.reject(`请输入正确的图片格式，多个用分号（;）分隔`);
                            }
                          });
                        }
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <Input style={{ width: '100%' }} disabled={!isEdit} />
                </Form.Item>
              </Col>
              <Col flex="0 0 220px">
                <Form.Item>格式以.开头，多个请用英文符号分号（;）分隔，例：.png;.jpg</Form.Item>
              </Col>
            </Row>
            <Row gutter={12} wrap={false}>
              <Col flex="0 0 120px">
                <Form.Item>限定条件3：</Form.Item>
              </Col>
              <Col flex="0 0 80px">
                <Form.Item>图片尺寸: </Form.Item>
              </Col>
              <Col flex="auto">
                <Form.Item name={[name, 'length']} key="length" label="长">
                  <Input
                    type="number"
                    min={0}
                    style={{ width: '100%' }}
                    suffix="px"
                    disabled={!isEdit}
                  />
                </Form.Item>
              </Col>
              <Col flex="auto">
                <Form.Item name={[name, 'width']} key="width" label="宽">
                  <Input
                    type="number"
                    min={0}
                    style={{ width: '100%' }}
                    suffix="px"
                    disabled={!isEdit}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={12} wrap={false}>
              <Col flex="0 0 120px">
                <Form.Item>限定条件4：</Form.Item>
              </Col>
              <Col flex="0 0 80px">
                <Form.Item>图片数量: </Form.Item>
              </Col>
              <Col flex="1 1 auto">
                <Form.Item name={[name, 'graphics']} key="graphics" label="不超过" colon={false}>
                  <Input
                    type="number"
                    min={0}
                    style={{ width: '100%' }}
                    suffix="张"
                    disabled={!isEdit}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={12} wrap={false}>
              <Col flex="0 0 120px">
                <Form.Item>限定条件5：</Form.Item>
              </Col>
              <Col flex="0 0 80px">
                <Form.Item>图片大小: </Form.Item>
              </Col>
              <Col flex="1 1 auto">
                <Form.Item name={[name, 'size']} key="size" label="不超过" colon={false}>
                  <Input
                    type="number"
                    min={0}
                    style={{ width: '100%' }}
                    suffix="Mb"
                    disabled={!isEdit}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Col>
        </Row>
      );
    }
  };

  const items: MenuProps['items'] = [
    {
      key: '1',
      label: <span>文本框</span>,
    },
    {
      key: '3',
      label: <span>上传图片</span>,
    },
  ];

  return (
    <Form form={form} name="dynamic_dir_temp_item" autoComplete="off">
      <Form.List name="dirConfig">
        {(fields, { add, remove }) => {
          return (
            <>
              <Form.Item>
                {isEdit ? (
                  <div key={'dir-mode'}>
                    <Dropdown
                      menu={{ items, onClick: ({ key }) => addDirTemp(key, add) }}
                      trigger={['click']}
                      placement="bottom"
                    >
                      <Button>
                        <PlusCircleOutlined />
                        添加目录形式
                      </Button>
                    </Dropdown>
                  </div>
                ) : null}
              </Form.Item>
              {fields.map(({ key, name, ...restField }) => {
                return (
                  <Row key={key}>
                    <Col span={24}>
                      <Space
                        key={key}
                        style={{
                          display: 'flex',
                          marginBottom: 8,
                        }}
                        align="baseline"
                      >
                        <Row gutter={12}>
                          {commonFormItems(name)}
                          {renderDirTemp(name, dirTemplateList[name])}
                        </Row>
                        {isEdit ? (
                          <MinusCircleOutlined onClick={() => removeDirTemp(name, remove)} />
                        ) : null}
                      </Space>
                    </Col>
                  </Row>
                );
              })}
            </>
          );
        }}
      </Form.List>
    </Form>
  );
};

export default forwardRef(DirTemplate);
